<template>
	<view class="nfc">
		<text v-if="visible" class="cuIcon-NFC- text-lg" @click="startSearchBeacon"></text>
		<view class="cu-load load-modal" v-if="loadModal" @click="stopSearchBeacon">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<text class="cuIcon-NFC- text-green radar"></text>
			<view class="gray-text tip-text slideShine">{{ value || tip }}</view>
		</view>
	</view>
</template>
<script>
import util from '@/common/util';
export default {
	data() {
		return {
			value: null,
			loadModal: false,
			timeout: 10,
			_uuid: null,
			ble_adv_status: false ,//外设广播状态
			mode:'central'//模式：central（中心设备/主机，默认）peripheral（外围设备/从机）
		};
	},
	props: {
		visible: {
			type: Boolean,
			default: true
		},
		uuid: {
			type: String,
			default: '12345678-1234-1234-1234-123456789ABC'
		},
		tip: {
			type: String,
			default: ''
		}
	},
	mounted() {},
	methods: {
		showModal: function() {
			this.loadModal = true;
		},
		hideModal: function() {
			this.loadModal = false;
		},
		//iBeacon是苹果公司推出的一项低耗能蓝牙技术，由蓝牙设备发射包含指定信息的信号，再由移动设备接收信号，从而实现近场通信。微信小程序2017年开始支持iBeacon，摇一摇附近就是基于iBeacon实现的，此外iBeacon还可以实现距离测量，本文将介绍如何基于微信小程序实现iBeacon测距
		startSearchBeacon: function(uuid) {
			this.loadModal = true;
			if (typeof uuid == 'string') {
				this._uuid = uuid;
			} else {
				this._uuid = this.uuid;
			}
			var that = this;
			//https://blog.csdn.net/qq_37936542/article/details/80482234
			//https://blog.csdn.net/qq_36711388/article/details/88934723
			//https://blog.csdn.net/baidu_38978508/article/details/101559518
			//https://blog.csdn.net/pwc1996/article/details/78083268
			that.searchBeacon();
			//监测蓝牙状态的改变
			/* uni.onBluetoothAdapterStateChange(function(res) {
				if (res.available) {
					//如果用户打开蓝牙，开始搜索IBeacon
					that.searchBeacon();
				}
			}); */
		},
		stopSearchBeacon: function(ev) {
			this.loadModal = false;
			uni.stopBeaconDiscovery({
				success: function() {
					if (typeof ev == 'function') {
						ev();
					}
					console.log('停止扫描ibeacon设备成功！');
					//searchBeacon();
				}
			});
		},
		/**
		 * 搜索beacons
		 */
		searchBeacon: function() {
			var that = this;
			//检测蓝牙状态
			uni.openBluetoothAdapter({
				success: function(res) {
					//蓝牙状态：打开
					uni.startBeaconDiscovery({
						//开始搜索附近的iBeacon设备
						uuids: [that._uuid], //参数uuid
						success: function(res) {
							console.log('开始扫描ibeacon设备');
							uni.onBeaconUpdate(function(res) {
								if (res && res.beacons && res.beacons.length > 0) {
									console.log('扫描到ibeacon设备');
									that.stopSearchBeacon();
									//监听 iBeacon 设备的更新事件
									//封装请求数据
									var beacons = res.beacons;
									/* var bleObj = {};
									bleObj.accuracy = beacons[0].accuracy;
									bleObj.rssi = beacons[0].rssi;
									bleObj.major = beacons[0].major;
									bleObj.minor = beacons[0].minor;
									bleObj.uuid = beacons[0].uuid;
									bleObj.proximity = beacons[0].proximity;
									that.value = bleObj; */
									/*调用计算rssi对应距离的函数
        var iRssi = Math.abs(arrayRSSI[i]); 
        var power = (iRssi-59)/(10*2.0); 
        var mm = Math.pow(10, power); 
        console.log(arraydeviceName[i]+"距离的位置是"+mm+"米");*/
									that.$emit('onMessage', beacons[0]);
									that.value = beacons[0];
									//console.log(that.value);
									that.loadModal = false;
								}
							});
						},
						fail: function(res) {
							console.log('扫描ibeacon设备失败:' + JSON.stringify(res));
							//先关闭搜索再重新开启搜索,这一步操作是防止重复wx.startBeaconDiscovery导致失败
							that.stopSearchBeacon(that.searchBeacon);
						}
					});
				},
				fail: function(res) {
					//蓝牙状态：关闭
					uni.showToast({ title: '请打开蓝牙', icon: 'none', duration: 2000 });
				}
			});
		},
		//作为ibeacon外设打开，暂时只支持微信。param参数对象{uuid:"",major:25666,minor:25666}
		//major (2 字节)：0 - 65535 的无符号整数，可以用来区分相同 UUID 的一组设备。
        //minor (2 字节)：0 - 65535 的无符号整数，可以用来区分有相同 UUID 和 major 的设备
		openBLEPeripheral(param) {
			//#ifdef MP-WEIXIN
			var that = this;
			wx.openBluetoothAdapter({
				mode: 'peripheral',
				success: res => {
					that.ble_adv_status = !that.ble_adv_status;
					if (!that.ble_adv_status) {
						that.stopAdvertising();
						return;
					}
					//console.log('openBluetoothAdapter success', res);
					this._createBLEPeripheralServer(param);
					/*
					wx.onBluetoothAdapterStateChange(function(res) {
						console.log('onBluetoothAdapterStateChange', res.available);
					});*/
				},
				fail: res => {
					console.log('打开蓝牙失败:' + JSON.stringify(res));
				}
			});
			//#endif
		},
		_createBLEPeripheralServer(param) {
			wx.createBLEPeripheralServer().then(res => {
				//console.log('createBLEPeripheralServer', res);
				//this.data.servers.push(res.server);
				this.server = res.server;
				this.serverId = this.server.serverId;
				this._startAdvertising(param);
			});
		},
		//开始广播
		_startAdvertising(param) {
			this.server
				.startAdvertising({
					advertiseRequest: {
						connectable: true,
						/* serviceUuids: [uuid1],
		        deviceName: 'hh',
		        serviceUuids: [uuid1]/*,
		        manufacturerData: [{
		          manufacturerId: '0x004c',
		          manufacturerSpecificData: typedArray.buffer
		        }]*/
						beacon: {
							uuid: param.uuid,
							major: param.major,
							minor: param.minor,
							measuredPower: 2 //要填，不然uni.onBeaconUpdate扫描到数组为空
						}
					},
					powerLevel: 'medium'
				})
				.then(
					res => {
						console.log('广播成功', res);
					},
					res => {
						console.log('广播失败: ', res);
					}
				);
		},
		//停止广播
		stopAdvertising() {
			this.server.stopAdvertising();
		}
	}
};
</script>
<style>
.nfc .cu-load.load-modal [class*='cuIcon-'] {
	font-size: 120rpx;
}
.nfc .cu-load.load-modal::after {
	border-left: 6upx solid #ffcc00;
}
.nfc .tip-text {
	font-size: 16rpx;
	position: absolute;
	top: 160rpx;
}
</style>
